package language.advanced.reflect;

import javassist.*;

class CreatePersonClass {
    public static void createPerson() throws Exception {
        //1.获取一个ClassPool对象
        ClassPool pool = ClassPool.getDefault();

        //2.使用ClassPool对象创建一个新类
        CtClass cc = pool.makeClass("javassist_.Person");

        //3.增加一个字段private String name,初始值为"walker"
        CtField field = new CtField(pool.get("java.lang.String"), "name", cc);
        field.setModifiers(Modifier.PRIVATE);
        cc.addField(field,CtField.Initializer.constant("walker"));

        //4.生成getter、setter方法
        cc.addMethod(CtNewMethod.getter("getName",field));
        cc.addMethod(CtNewMethod.setter("setName",field));

        //5.添加无参构造器
        CtConstructor cons = new CtConstructor(new CtClass[]{}, cc);
        cons.setBody("{name = \"walker\";}");
        cc.addConstructor(cons);

        //6.添加有参构造器
        cons = new CtConstructor(new CtClass[]{pool.get("java.lang.String")},cc);
        // $0 = this $1,$2,$3... 代表方法参数
        cons.setBody("{$0.name = $1;}");
        cc.addConstructor(cons);

        //7.创建一个名为personInfo的方法,无参数，无返回值，输出name值
        CtMethod method = new CtMethod(CtClass.voidType, "personInfo", new CtClass[]{}, cc);
        method.setModifiers(Modifier.PUBLIC);
        method.setBody("{System.out.println(name);}");
        cc.addMethod(method);

        //8.将创建的类编译为.class文件
        cc.writeFile("F:\\JAVA\\javassist_asm\\src\\main\\java");
    }

    public static void main(String[] args) {
        try {
            createPerson();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}